$(function(){
	$('.mc').css('display','none');
	$('#categorys').hover(function(){
		$(this).children('.mc').toggle();
	});
	getProductInfo();
	$('#addNum').click(function(){
		addProduct();
		return false;
	});
	$('#minusNum').click(function(){
		minusProduct();
		return false;
	});
	 $('#summary .fore1').mousemove(function(){
	 	$(this).addClass('hover');   
	 	$('#summary .fore1 dl dd').show();
	 });
 	$('#summary .fore1').mouseout(function(){     
 		$('#summary .fore1 dl dd').hide();
 		$(this).removeClass('hover');
 	});
 	$('#retunsTimes').click(function(){
 		$("html,body").animate({scrollTop: $('#feedback').offset().top},"slow");
 	})
 	
 	$('#mcTitle').html('推荐商品');
 	$('#PRODUCT_ID').val($Util.getQueryString(document.location.search,'id'));
 	loadStar();
 	getRecommendList();
 	getPlateProductList();
 	getBrowsedMcList();
 	getCommentList();
 	getCommentCount();
 	getSession();
 	
 	var str = [' &gt;&nbsp;<a href="/product/list.html?is_all=1">母婴</a>'].join('');
	$('#linkDesc').after(str);
});

function getSession(){
	var url = '/json?action=GET_MEMBER_SESSION_ACTION';
	$.post(url,{},function(data){
		if(data.success){
			var obj  = data.root.MEMBER_SESSION;
			if(obj == undefined){
				$('#loginBtn').show();
			}
			else{
				$('#feedBtn').show();
			}
		}
	},'json');	
}

function toLogin(){
	location.href = "../user/login.html?to_url="+location.href;
}

function addFavorite(title, url) {
	try {
		window.external.addFavorite(url, title);
	} catch (e) {
		try {
			window.sidebar.addPanel(title, url, '');
		} catch (e) {
			alert('收藏失败');
		}
	}
}

function listenerKeypress(){
	return ((event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 8);
}

function listenerKeyUp(){
	var obj = $('#AmountVlaue');
	var v = obj.val();
	if(v.length == 0){
		obj.val(1);
	}
}

function addCart(btn){
	var url = '/json?action=ADD_PRODUCT_TO_CART_ACTION';
	$.post(url,{
			PRODUCT_ID:$Util.getQueryString(document.location.search,'id'),
			QTY : $.trim($('#AmountVlaue').val())
		},function(data){
		if (data.success) {
			var cart = data.root.CART.rs[0];
			$('#cart_count').html(cart.ITEMS);
			$('#cart_amount').html("￥" + cart.AMOUNT);
			var tip = $('#add_cart_tip');
			showTip(tip,btn,0, 1);
			getCart();
		} else {
			alert(data.errors.errmsg);
		}
	},'json');
}

var timer;
function showTip(tip, btn, left, top){
	var offset = $(btn).offset();
	tip.css('left', offset.left - left);
	tip.css('top', offset.top - top);
	tip.show();
	
	if (timer) {
		clearTimeout(timer);
	}
	timer = setTimeout("closeTip()", 3000);
}

function closeTip() {
	$('#add_cart_tip').fadeOut('slow');
	timer=null;
}

function getProductInfo() {
	var url = '/json?action=QUERY_T_PRODUCT_BY_CONDITION_ACTION';
	$.post(url,{PRODUCT_ID:$Util.getQueryString(document.location.search,'id')},function(data){
		if (data.success) {
			var oObjProduct = data.root.T_PRODUCT;
			if (!oObjProduct) {
				location.href = 'nofound.html';
				return;
			} else {
				var obj = oObjProduct.rs[0];
				$('#productName').html(obj.PRODUCT_NAME);
				$('#productNo').after(obj.PRODUCT_NO);
				$('#marketPrice').html('￥'+obj.MARKET_PRICE);
				$('#memberPrice').html('￥'+obj.MEMBER_PRICE);
				$('#memberPrice').after('购买此商品可得'+$Math.fix(obj.POINTS,0)+'积分');
//				$('#retunsTimes').html('(已有'+(obj.RETUNS_TIMES == null ? 0 : obj.RETUNS_TIMES)+'人评价)');
				$('#topImg').attr('src','../upload/product/'+obj.PRODUCT_NO+'.jpg').attr('jqimg','../upload/product/'+obj.PRODUCT_NO+'.jpg');
				$('#showBigImg').attr('href','../upload/product/'+obj.PRODUCT_NO+'.jpg');
				$('#productImgs').append('<li><img src="../upload/product/'+obj.PRODUCT_NO+'.jpg" /></li>');
				var oObjDetail = data.root.T_PRODUCT_DETAIL.rs[0];
				for(var i = 0; i < oObjDetail.DETAIL_COUNT; i++){
					$('#productImgs').append('<li><img src="../upload/product/'+obj.PRODUCT_NO+'_N_'+(i+1)+'.jpg" /></li>');
				}
				$('.jqzoom').jqueryzoom({
					xzoom: 400,
					yzoom: 400,
					offset: 10,
					position: 'right',
					preload: 1,
					lens: 1
				});
				$('#spec-list').jdMarquee({
					deriction: 'left',
					width: 352,
					height: 56,
					step: 2,
					speed: 4,
					delay: 10,
					control: true,
					_front: '#spec-right',
					_back: '#spec-left'
				});
				$('#spec-list img').bind('mouseover', function() {
					var src = $(this).attr('src');
					$('#spec-n1 img').eq(0).attr({
						src: src.replace('\/n5\/', '\/n1\/'),
						jqimg: src.replace('\/n5\/', '\/n0\/')
					});
					$(this).css({
						'border': '2px solid #ff6600',
						'padding': '1px'
					});
				}).bind('mouseout', function() {
					$(this).css({
						'border': '1px solid #ccc',
						'padding': '2px'
					});
				});
				var bo = new $Obj.browseObj();
				bo.id = obj.PRODUCT_ID;
				bo.name = obj.PRODUCT_NAME;
				bo.price = obj.MEMBER_PRICE;
				bo.imgUrl = '/upload/product/'+obj.PRODUCT_NO+'.jpg';
				
				// 新增浏览记录
				var mcRs = $.cookie('browsedMc');
				if (!mcRs) {
					mcRs = '[]';
				}
				var res = JSON.parse(mcRs);
				if (res.length == 0) {
					res.push(JSON.parse(JSON.stringify(bo)));
				} else {
					if (res.length > 5) {
						res.shift();
					} 
					var isExist = false;
					$.each(res,function(i,n){
						if (n.id == bo.id) {
							isExist = true;
							return false;
						}
					});
					if (!isExist) {
						res.push(JSON.parse(JSON.stringify(bo)));
					}
				}
				$.cookie('browsedMc',JSON.stringify(res),{expires:365});
			}
			
			if (oObjDetail) {
				$('#myTab1_Content0').html(oObjDetail.PRODUCT_DESC == null ? '' : oObjDetail.PRODUCT_DESC);
//				$('#myTab1_Content1').html(obj.PRODUCT_SPEC == null ? '' : obj.PRODUCT_SPEC);
			}
			for(var i = 0; i < oObjDetail.DESC_COUNT; i++){
				$('#myTab1_Content0').append('<img src="../upload/product/'+obj.PRODUCT_NO+'_'+(i+1)+'.jpg" />');
			}
		}
	},'json');
}

function getRecommendList() {
	var url = '/json?action=QUERY_T_PLATE_PRODUCT_ACTION';
	$UI.listPage(url,'T_PLATE_PRODUCT','#buyedList',printRecommendRes,'');
}

function printRecommendRes(obj,result,i,n,total) {
	if (result && obj.PLATE_CODE == '1014' && obj.PRODUCT_LIST.length>0) {
		$.each(obj.PRODUCT_LIST,function(j,m){
			if (j+1>4) return false;
			var appendStr = [
				'<li>',
				'<div>',
				'<p>','<a href="file.html?id=',m.productId,'">',m.productName,'</a>','</p>',
				'<p class="fb">￥',m.memberPrice,'</p>',
				'</div>',
				'<a href="file.html?id=',m.productId,'">','<img src="../upload/product/'+m.productNo+'.jpg" width="160" height="160"/>','</a>',
				'</li>'
			].join('');
			$(result).append(appendStr);
		});
	}
}

function getPlateProductList() {
	var url = '/json?action=QUERY_T_PLATE_PRODUCT_ACTION';
	$UI.listPage(url,'T_PLATE_PRODUCT','#newList',printPlateProductRes,'');
}

function printPlateProductRes(obj,result,i,n,total) {
	var panel = '';
	switch(obj.PLATE_CODE) {
		// 新品上市
		case '1012':
			panel = '#newList';
			break;
		// 热销商品
		case '1013':
			panel = '#hotItemList';
			break;
		default:
			break;
	}
	if (panel && obj.PRODUCT_LIST.length>0) {
		$.each(obj.PRODUCT_LIST,function(j,m){
			if ($(panel+'>li').length>2) return true;
			var appendStr = [
				'<li>',
				'<a href="file.html?id=',m.productId,'">','<img src="../upload/product/'+m.productNo+'.jpg" width="160" height="160"/>','</a>',
				'<p>','<a href="file.html?id=',m.productId,'">',m.productName,'</a>','</p>',
				'<p class="cDGray">金麒价：','<strong>￥',m.memberPrice,'</strong>','</p>',
				'</li>'
			].join('');
			$(panel).append(appendStr);
		});
	}
}

function getBrowsedMcList() {
	var mcRs = $.cookie('browsedMc');
	if (mcRs) {
		var res = JSON.parse(mcRs);
		var newRes = res.reverse();
		var divStr = '';
		$.each(newRes,function(i,n){
			divStr += [
				'<li>',
				'<a href="file.html?id=',n.id,'">','<img src="',n.imgUrl,'" width="160" height="160"/>','</a>',
				'<p>','<a href="file.html?id=',n.id,'">',n.name,'</a>','<p class="cDGray">金麒价：<strong>￥',n.price,'</strong>','</p>',
				'</li>'
			].join('');
		});
		$('#browseMcList').append(divStr);
	}
}

function addProduct() {
	var k;
	k = $('#AmountVlaue').val();
	$('#AmountVlaue').attr('value',++k);
}

function minusProduct() {
	var k;
	k = $('#AmountVlaue').val();
	if (k > 1)
		$('#AmountVlaue').attr('value',--k);
}

function fillSend(province) {
	$('#sendProvince').html(province);
}

function nTabs(thisObj, Num) {
	if (thisObj.className == 'active')
		return;
	var tabObj = thisObj.parentNode.id;
	var tabList = document.getElementById(tabObj).getElementsByTagName('li');
	for (i = 0; i < tabList.length; i++) {
		if (i == Num) {
			thisObj.className = 'active';
			document.getElementById(tabObj + '_Content' + i).style.display = 'block';
		} else {
			tabList[i].className = 'normal';
			document.getElementById(tabObj + '_Content' + i).style.display = 'none';
		}
	}
}

function subFrm(){
	var star = $('#score').val();
	if(star == 0){
		$('#star_tip').addClass('red');
		$('#star_tip').html("分享下您的感受，给我们打分吧！");
		return;
	}
//	var text = $.trim($('#comment_text').val());
//	$('#comment_tip').html("");
//	if(text.length == 0){
//		$('#comment_tip').html("给我们的商品说点什么吧！");
//		return; 
//	}
	
	var options = {
	    dataType: 'json',
    	iframe:	false,
	    success: function(data) {
	    	if(data.success){
	    		$('#frm').resetForm();
	    		getCommentList();
	      	}else{
	      		alert(data.errors.errmsg);
	      	}
	   	}
	};
	$.ajaxSetup({contentType:'application/x-www-form-urlencoded;charset=utf-8'});
    $('#frm').ajaxSubmit(options);
}

var maxLength = 300;
function countWord(){
	var text = $.trim($('#comment_text').val());
	
	var e = e || event;
	var currKey = e.keyCode||e.which||e.charCode;
	if(currKey == 8 || currKey == 46){
		if(maxLength - text.length <= 0){
			$('#num').html('0');
		}
		else{
			$('#num').html(maxLength - text.length);
		}
		return true;
	}
	
	if(maxLength - text.length <= 0){
		$('#num').html('0');
		return false;
	}
	$('#num').html(maxLength - text.length);
	return true;
}


function loadStar(){
    var oStar = document.getElementById("star");
	var aLi = oStar.getElementsByTagName("li");
	var oUl = oStar.getElementsByTagName("ul")[0];
	var oSpan = oStar.getElementsByTagName("span")[1];
	var oP = oStar.getElementsByTagName("p")[0];
	var i = iScore = iStar = 0;
	var aMsg = [
			"很不满意|差得太离谱，与描述的严重不符，非常不满", 
			"不满意|部分有破损，与描述的不符，不满意",
			"一般|质量一般，没有描述的那么好", 
			"满意|质量不错，与描述的基本一致，还是挺满意的",
			"非常满意|质量非常好，与描述的完全一致，非常满意"];

	for (i = 1; i <= aLi.length; i++) {
		aLi[i - 1].index = i;
		//鼠标移过显示分数
		aLi[i - 1].onmouseover = function() {
			fnPoint(this.index);
			//浮动层显示
			oP.style.display = "block";
			//计算浮动层位置
			oP.style.left = oUl.offsetLeft + this.index * this.offsetWidth - 104 + "px";
			//匹配浮动层文字内容
			oP.innerHTML = "<em><b>" + this.index + "</b> 分 "+ aMsg[this.index - 1].match(/(.+)\|/)[1] + "</em>"+ aMsg[this.index - 1].match(/\|(.+)/)[1];
		};
		//鼠标离开后恢复上次评分
		aLi[i - 1].onmouseout = function() {
			fnPoint();
			//关闭浮动层
			oP.style.display = "none";
		};
		//点击后进行评分处理
		aLi[i - 1].onclick = function() {
			$('#star_tip').removeClass('red');
			iStar = this.index;
			$('#score').val(this.index);
			oP.style.display = "none";
			oSpan.innerHTML = "<strong>" + (this.index) + " 分</strong> ("+ aMsg[this.index - 1].match(/\|(.+)/)[1] + ")";
		}
		//评分处理
		function fnPoint(iArg) {
			//分数赋值
			iScore = iArg || iStar;
			for (i = 0; i < aLi.length; i++){
				aLi[i].className = i < iScore ? "on" : "";
			}
		}
	}
}

function getCommentList() {
	var url = '/json?action=QUERY_T_PRODUCT_COMMENT_PAGERBY_PRODUCT_ID_ACTION&PRODUCT_ID=' + $Util.getQueryString(document.location.search,'id');
	var pageSize = 10;
	var defaultHtml = '<li style="text-align: center">还没有人评价，您来当第一个评论者吧！</li>';
	var current = $Util.getQueryString(document.location.search,'current');
	$UI.changePage(url,pageSize,'T_PRODUCT_COMMENT','#comment_list',printComment,'#pager',defaultHtml,current);
}

function printComment(obj,result,i,n,len,c,t) {
	if (t) {
		$('#totalProducts').html('共<strong>'+t+'</strong>个评论');
		$('#pageShow').html(c+'/'+(Math.floor(t/25)+1));
	}
	var div = [
		'<li>',
			'<img src="../images/pic_tx02.jpg" />',
			'<div>',
				'<span>评论时间：',$Util.toChar(obj.COMMENT_DATE,'yyyy-mm-dd hh24:mi:ss'),'</span>',
				'<p class="fb">',obj.MEMBER_ACCOUNT,'：</p>',
				'<p>',obj.COMMENT_TEXT,'</p>',
				'<p><em class="star sa',obj.SCORE,'"></em></p>',
			'</div>',
		'</li>'
	].join('');	
	$(result).append(div);
}

function getCommentCount(){
	var url = '/json?action=QUERY_T_PRODUCT_COMMENT_COUNT_ACTION&PRODUCT_ID=' + $Util.getQueryString(document.location.search,'id');
	$.post(url,{},function(data){
		if(data.success){
			var obj = data.root.T_COMMENT_COUNT.rs[0];
			var star_1 = obj.STAR_1;
			var star_2 = obj.STAR_2;
			var star_3 = obj.STAR_3;
			var star_4 = obj.STAR_4;
			var star_5 = obj.STAR_5;
			var count = obj.COUNT;
			$('#retunsTimes').html('(已有'+count+'个评价)');
			
			var avg = (0.2 * star_1 + 0.4 * star_2 + 0.6 * star_3 + 0.8 * star_4 + 1 * star_5)/count;
			avg = parseInt(avg * 10);
			var index = 5;
			if(avg <= 2 && avg > 0){
				index  = 1;
			} else if(avg <= 4 && avg > 2){
				index  = 2;
			} else if(avg <= 6 && avg > 4){
				index  = 3;
			} else if(avg <= 8 && avg > 6){
				index  = 4;
			} else if(avg <= 10 && avg > 9){
				index  = 5;
			} else if(avg > 10){
				index  = 5;
			}
			$('#avg_star').removeClass('sa5').addClass('sa'+index);
			$('#star_1').css({'width' : parseInt(star_1/count*100)+'%'});
			$('#star_2').css({'width' : parseInt(star_2/count*100)+'%'});
			$('#star_3').css({'width' : parseInt(star_3/count*100)+'%'});
			$('#star_4').css({'width' : parseInt(star_4/count*100)+'%'});
			$('#star_5').css({'width' : parseInt(star_5/count*100)+'%'});
			
			$('#star_1_count').html('(' + star_1 + ')');
			$('#star_2_count').html('(' + star_2 + ')');
			$('#star_3_count').html('(' + star_3 + ')');
			$('#star_4_count').html('(' + star_4 + ')');
			$('#star_5_count').html('(' + star_5 + ')');
		}
	},'json');
}